#!/bin/bash

if [ $# -lt 1 ] ; then
    echo usage:
    echo $0 play_url
    echo
    echo example:
    echo $0 "http://www.tudou.com/playlist/p/a65568.html"

    exit 1
fi
play_url=$1

# gen random curl output file name
res_file=`date +%s`.html
# download resource file
curl "$play_url" -o $res_file
# get play title
title=`grep ^,atitle $res_file | sed 's#.*= "##g' | sed 's#".*##g'`
# get iid list
list=`grep ^iid: $res_file | awk -F: '{print $2}'`

USER_AGENT="Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"

mkdir -p var.$title
mkdir -p ret.$title

i=0
for iid in $list ; do
    i=$((i+1))
    url_1="http://v2.tudou.com/v?hd=4&vn=02&si=10000&it=$iid&noCache=73555&pw=&st=1%2C2%2C3%2C5&ui=0"
    echo wget --user-agent="$USER_AGENT" $url_1 -O "var.$title/$iid.var"
    wget --user-agent="$USER_AGENT" $url_1 -O "var.$title/$iid.var"

    url_2=`cat "var.$title/$iid.var" | awk -F "</f>" '{print $1}' | sed "s#.*http#http#g"`
    echo wget --user-agent="$USER_AGENT" $url_2 -O "ret.$title/$i.f4v"
    wget --user-agent="$USER_AGENT" $url_2 -O "ret.$title/$i.f4v"

    sleep 10
done
